package br.edu.infnet.dao;


import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import br.edu.infnet.hibernate.util.HibernateUtil;
import br.edu.infnet.modelo.Aluno;

public class AlunoDao {

	private Session session;
	private Query query;

	public void inserir(Aluno u) {
		try {
			session = HibernateUtil.getSession();
			session.beginTransaction();
			session.save(u);
			session.getTransaction().commit();
		} catch (Exception e) {
			 session.getTransaction().rollback();
			 System.out.println("Falha ao inserir. Erro: " + e.getMessage());
		}finally{
			session.close();
		}
	}
	
	public boolean validar(Aluno u){
		boolean resultado = false;
		try {
			session = HibernateUtil.getSession();
			session.beginTransaction();
			query = session.createQuery("from Aluno u where u.login = :user and u.senha =  :pass");
			query.setString("user", u.getLogin());
			query.setString("pass", u.getSenha());
			resultado = !query.list().isEmpty();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return resultado;
		
	}
	
	public Aluno carregar(int codigo){
		Aluno a = new Aluno();
		session = HibernateUtil.getSession();
		session.beginTransaction();
		query = session.createQuery("from Aluno u where u.matricula = :cod");
		query.setInteger("cod", codigo);
		a = (Aluno) query.list();
		return a;
	}
	
	
	@SuppressWarnings("unchecked")
	public List<Aluno> listarAlunos(){
		List<Aluno> lista = new ArrayList<Aluno>();
		try {
			session = HibernateUtil.getSession();
			session.beginTransaction();
			lista = session.createCriteria(Aluno.class).list();
			session.getTransaction().commit();
		} catch (Exception e) {
			 session.getTransaction().rollback();
			 System.out.println("Falha ao gerar lista de alunos. Erro: " + e.getMessage());
			 e.printStackTrace();
		}
		return lista;
	}
	
//	
//	public boolean validarLogin(Usuario usuario) {
//		boolean achou = false;
//		try {
//			Connection conexao = getConexao();
//			PreparedStatement pstm = conexao
//					.prepareStatement("Select id, nome from tabusuario where login = ? and senha =? ");
//			pstm.setString(1, usuario.getLogin());
//			pstm.setString(2, usuario.getSenha());
//
//			ResultSet rs = pstm.executeQuery();
//			
//			achou = rs.next();
//			pstm.close();
//			conexao.close();
//
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return achou;
//	}

}
